package bch.netty.handler.outbound;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Slf4j
public class OutBoundHandlerA extends ChannelOutboundHandlerAdapter {

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        if (msg instanceof TextWebSocketFrame frame) {
            log.info("【OutBoundHandlerA】 decorate message {}" ,frame.text());
            // 修改文本内容
            TextWebSocketFrame newFrame = new TextWebSocketFrame("【OutBoundHandlerA】 " + frame.text());
            super.write(ctx, newFrame, promise);
            // 注意释放原 frame
            frame.release();
            // 这种仅仅是服务器可见的log信息 客户端不可见
//            promise.setFailure(new Exception("业务异常"));
            // fire到全局异常处理器处理
//            ctx.fireExceptionCaught(new Exception("业务异常"));
        } else {
            super.write(ctx, msg, promise);
        }
    }

}
